<template>
	<view class="page">
		<global-contact></global-contact>
		<view class="area">
			<u--textarea :height="160" maxlength="900" v-model="contents" placeholder="说点有趣的事情吧..."></u--textarea>
		</view>
		<view class="upload">
			<!-- 	<u-upload
				:fileList="fileList1"
				@afterRead="afterRead"
				@delete="deletePic"
				name="1"
				multiple
				:maxCount="10"
				:previewFullImage="true"
			></u-upload> -->
			<!-- showImg+ -->
			<!-- <view class="succImg" v-for="(item,index) in imageList" :key="index">
				<image :src="showImg+item" mode="aspectFill"></image>
				 <view class="icon" @click="del(index)">
				 	<u-icon name="close-circle-fill"  size="28"></u-icon>
				 </view>
			</view> -->
			<!-- list  drag -->
			<view class="drag-wrap">
				<!-- <dragSort @navTo="navTo" :list.sync="list" label="name" :columnNum="4" :columnSpace="0" :rowHeight="300" :rowSpace="0"></dragSort> -->
				<!-- <dragSort :list.sync="list" label="name" :columnNum="4" :columnSpace="20" :rowHeight="200" :rowSpace="20"></dragSort> -->
				<dragSort :list.sync="list" label="name" :columnNum="3" :columnSpace="20" :rowHeight="200"
					:rowSpace="20"></dragSort>
				<!-- <view>排序后的id顺序如下：</view>
				<view>{{list.map(item => item.id).join('，')}}</view> -->
			</view>

			<view class="succImg" @click="chooseImg">
				<image src="https://www.atuanjian.com/appletStatic/static/detail/add.png" mode="aspectFill"></image>
			</view>
		</view>
		<view class="flex" @click="chooseLocation">
			<view class="flex-1">
				<u-icon name="map" size="20"></u-icon>
				{{ location.name ? location.name : '所在位置' }}
			</view>
			<u-icon name="arrow-right" size="20" style="margin-right: 20rpx;"></u-icon>
		</view>
		<view class="sub">
			<view class="btn" @click="submit">发布</view>
		</view>

	</view>
</template>

<script>
import {
	dynamic,
	publish
} from '@/utils/request.js'
// import dragSort from '../components/dragSort.vue'
import dragSort from '../components/drag.vue'

export default {
	components: {
		dragSort
	},
	data() {
		return {
			fileList1: [],
			upload: '',
			userInfo: JSON.parse(uni.getStorageSync('userInfo') || '{}'),
			// img_arr:'',
			contents: '',
			flag: false,
			imageList: [],
			showImg: '',
			location: {},
			initId: 0,
			list: []
		}
	},
	components: {
		dragSort
	},
	methods: {
		chooseLocation() {
			uni.chooseLocation({
				success: (res) => {
					console.log('选择位置成功:', res);
					this.location = {
						name: res.name,
						address: res.address,
						latitude: res.latitude,
						longitude: res.longitude
					};
				},
				fail: (err) => {
					console.error('选择位置失败:', err);
					uni.showToast({
						title: '选择位置失败，请检查权限设置',
						icon: 'none'
					});
				}
			});
		},
		async publish(data) {
			return await publish(data)
		},
		submit() {
			if (!this.contents) {
				uni.showToast({
					title: '请输入内容',
					icon: 'none'
				})
				return
			}
			if (this.list.length == 0) {
				uni.showToast({
					title: '请上传内容',
					icon: 'none'
				})
				return
			}
			if (this.list.length > 0) {
				let currentImg = []
				this.list.forEach(val => {
					currentImg.push(val.url)
				})
				// return
				this.imageList = currentImg
			}
			if(!this.location.name){
				uni.showToast({
					title:"请选择位置！",
					icon:'none'
				})
				return ;
			}
			let data = {
				token: this.userInfo.token,
				img_arr: this.imageList,
				contents: this.contents,
				address_name:this.location.name,
				address:this.location.address,
				lat:this.location.latitude,
				lng:this.location.longitude
			}
			if (this.flag) {
				return
			}
			uni.showLoading()
			this.flag = true
			this.publish(data).then(res => {
				console.log('发布成功', res)
				if (res) {
					uni.hideLoading()
					// if (res.data.code == 200) {
					uni.showToast({
						title: '发布成功',
						duration: 1500
					})
					uni.setStorageSync('upload', '1')
					setTimeout(() => {
						uni.navigateBack({
							delta: 1
						})
					}, 1500)
					this.flag = false
				}else{

				}

				// }
			})
		},
		del(index) {
			this.imageList.splice(index, 1)
		},
		chooseImg() {
			let t = this;
			uni.chooseImage({
				sizeType: ['compressed'],
				success: (chooseImageRes) => {
					console.log('chooseImageRes', chooseImageRes)
					let tempFilePaths = chooseImageRes.tempFilePaths;
					console.log('tempFilePaths', tempFilePaths)
					tempFilePaths.forEach(val => {
						uni.uploadFile({
							url: t.upload + 'file/imageUpload', //仅为示例，非真实的接口地址
							filePath: val,
							name: 'file',
							formData: {
								file: val,
								token: t.userInfo.token,
							},
							success: (uploadFileRes) => {
								console.log('uploadFileRes:', uploadFileRes)
								let data = JSON.parse(uploadFileRes.data)
								// console.log('res',data)
								if (data.code != 200) {
									uni.showToast({
										title: data.msg,
										icon: 'none',
										duration: 3000
									})
								} else {
									// console.log(data);
									t.imageList.push(data.path)
									t.initId += 1
									t.list.push({
										url: data.path,
										id: t.initId
									})
									console.log('上传的图片', t.imageList, t.list)
								}
							}
						});
					})
				}
			});
		},
		// 删除图片 *
		deletePic(event) {
			this[`fileList${event.name}`].splice(event.index, 1)
		},
		// 新增图片 * 
		async afterRead(event) {
			// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
			let lists = [].concat(event.file)
			console.log('event', event)
			let fileListLen = this[`fileList${event.name}`].length
			lists.map((item) => {
				console.log('item', item)
				this[`fileList${event.name}`].push({
					...item,
					status: 'uploading',
					message: '上传中'
				})
			})
			for (let i = 0; i < lists.length; i++) {
				const result = await this.uploadFilePromise(lists[i].url)
				console.log('result', result)
				if (result) {
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}

			}
			console.log(this.fileList1)
		},
		// *
		uploadFilePromise(url) {
			console.log('上传参数', url)
			return new Promise((resolve, reject) => {
				let a = uni.uploadFile({
					url: this.upload + 'file/imageUpload', // 仅为示例，非真实的接口地址
					filePath: url,
					name: 'file',
					formData: {
						file: url,
						token: this.userInfo.token,
					},
					success: (res) => {
						// console.log('103',JSON.parse(res.data))
						let data = JSON.parse(res.data)
						// console.log('res',JSON.parse(res.data).path)
						// setTimeout(() => {
						// 	resolve(JSON.parse(res.data).path)
						// }, 200)
						if (data.code == 403) {
							uni.showToast({
								title: data.msg,
								icon: 'none',
								duration: 3000
							})
							resolve('')
						} else {
							resolve(data.path)
						}
					}
				});
			})
		},
	},
	onLoad(option) {
		this.upload = this.$config.upLoadApi;
		this.showImg = this.$config.showImgApi;
		if (option.url) {
			console.log(option.url)
			this.imageList.push(option.url)
			this.initId += 1
			this.list.push({
				url: option.url,
				id: this.initId
			})
		}
	}
}
</script>

<style lang="scss" scoped>
page {
	background-color: #F8F8F8;
}

.flex {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 0 40rpx;
	background: #FFFFFF;

	.flex-1 {
		display: flex;
		align-items: center;
		margin-left: 20rpx;
	}
}

.upload {
	padding: 0 20rpx 30rpx;
	background-color: #FFFFFF;
	display: flex;
	justify-content: flex-start;
	align-items: center;
	flex-flow: row wrap;

	.succImg {
		position: relative;
		width: 200rpx;
		height: 200rpx;
		margin-top: 20rpx;
		margin-right: 30rpx;
		margin-bottom: 20rpx;

		image {
			width: 200rpx;
			height: 200rpx;
			margin-right: 10rpx;
		}

		.icon {
			position: absolute;
			top: 0;
			right: 0;

		}
	}
}

.u-border {
	border: none !important;
}

.sub {
	.btn {
		width: 90%;
		border-radius: 20rpx;
		text-align: center;
		line-height: 80rpx;
		background-color: #FFB850;
		color: #FFFFFF;
		font-size: 26rpx;
		margin: 40rpx auto;
	}
}
</style>